package auth_dao

import (
	"admin-system/internal/models/auth_model"
	"context"
	"gorm.io/gorm"
)

type PermissionDao struct {
	db *gorm.DB
}

func NewPermissionDao(db *gorm.DB) *PermissionDao {
	return &PermissionDao{
		db: db,
	}
}

// GetAllPermissions 查询所有权限
// @description 后台列表查询所有权限
func (p *PermissionDao) GetAllPermissions(ctx context.Context) ([]auth_model.Permission, error) {
	var permissions []auth_model.Permission
	err := p.db.WithContext(ctx).Find(&permissions).Error
	return permissions, err
}

// GetPermissionByRoleId 查询指定角色下的权限
// @description 查询指定角色下的权限
// @param roleId
func (p *PermissionDao) GetPermissionByRoleId(ctx context.Context, roleId int64) ([]auth_model.Permission, error) {
	var permissions []auth_model.Permission
	err := p.db.WithContext(ctx).
		Joins("JOIN role_permissions ON role_permissions.permission_id = permissions.id").
		Where("role_permissions.role_id = ?", roleId).
		Find(&permissions).Error
	return permissions, err
}

// SavePermission 保存权限
// @description 保存权限（新增、修改）
// @param permission
func (p *PermissionDao) SavePermission(ctx context.Context, permission *auth_model.Permission) (*auth_model.Permission, error) {
	permissionDB := p.db.WithContext(ctx)
	if permission.ID > 0 {
		if err := permissionDB.Model(&auth_model.Permission{}).Where("id=?", permission.ID).Updates(permission).Error; err != nil {
			return nil, err
		}
		return permission, nil
	}
	if err := permissionDB.Model(&auth_model.Permission{}).Create(permission).Error; err != nil {
		return nil, err
	}
	return permission, nil
}

// DelPermission 删除权限
// @description 删除权限
// @param id
func (p *PermissionDao) DelPermission(ctx context.Context, id int64) error {
	return p.db.WithContext(ctx).Where("id = ?", id).Delete(&auth_model.Permission{}).Error
}
